//
//  HScanView.m
//  HTanzhi
//
//  Created by 陈贵 on 15/11/18.
//  Copyright © 2015年 hzj. All rights reserved.
//

#import "HScanView.h"
#import "Masonry.h"
#import <AVFoundation/AVFoundation.h>
#import "HCreatImage.h"

@interface HScanView ()<AVCaptureMetadataOutputObjectsDelegate>

@property (nonatomic ,strong) UIView *scanView;
@property (nonatomic ,strong) UIImageView *scanlineView;

///拍摄会话
@property (nonatomic ,strong) AVCaptureSession * session;
///输入设备
@property (nonatomic ,strong) AVCaptureDeviceInput * deviceInput;
///输出数据
@property (nonatomic ,strong) AVCaptureMetadataOutput *metadataOutput;
///预览视图
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
///绘图层
@property (nonatomic ,strong) CALayer *drawLayer;

@property (nonatomic ,strong) UILabel *mylable;

///计时
@property (nonatomic ,assign) CFAbsoluteTime time;

@property (nonatomic, strong) MASConstraint *bottomMASConstraint;
@property (nonatomic, strong) NSLayoutConstraint *bottomConstraint;

@end

@implementation HScanView

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    self.mylable = lable;
    [self.view addSubview:lable];
    
    //生成二维码按钮
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"生成" style:UIBarButtonItemStylePlain target:self action:@selector(buldTheScanImage)];
    self.navigationItem.rightBarButtonItem = item ;
    
    //设置UI
    [self setUI];
    //扫描
    [self addScanFoundation];
    
}
//生成二维码
- (void)buldTheScanImage{
    HCreatImage *iv = [[HCreatImage alloc]init];
    iv.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:iv animated:YES];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setAnimation];
}

#pragma UI设置
///设置UI
- (void) setUI{
    
    CGFloat w = 200;
    CGFloat h = 200;
    UIView *scanView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, w, h)];
    scanView.center = self.view.center;
    scanView.backgroundColor = [UIColor clearColor];
    scanView.clipsToBounds = YES;
    self.scanView = scanView;
    [self.view addSubview:scanView];

    
    UIImageView *borderView = [[UIImageView alloc]initWithFrame:scanView.bounds];
    [borderView setImage:[UIImage imageNamed:@"qrcode_border"]];
    [scanView addSubview:borderView];
    
    UIImageView *scanlineView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -h, w, h)];
    [scanlineView setImage:[UIImage imageNamed:@"qrcode_scanline_qrcode"]];
    scanlineView.backgroundColor = [UIColor clearColor];
    self.scanlineView = scanlineView;
    [scanView addSubview:scanlineView];
    
    self.scanlineView.translatesAutoresizingMaskIntoConstraints = NO;
    NSLayoutConstraint *leftC = [NSLayoutConstraint constraintWithItem:self.scanlineView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self.scanView attribute:NSLayoutAttributeLeading multiplier:1 constant:0];
    //右
    NSLayoutConstraint *rightC = [NSLayoutConstraint constraintWithItem:self.scanlineView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.scanView attribute:NSLayoutAttributeTrailing multiplier:1 constant:0];
    //上
    NSLayoutConstraint *bottomC= [NSLayoutConstraint constraintWithItem:self.scanlineView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.scanView attribute:NSLayoutAttributeTop multiplier:1 constant:0];
    self.bottomConstraint = bottomC;
    //高
    NSLayoutConstraint *heightC = [NSLayoutConstraint constraintWithItem:self.scanlineView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.scanView attribute:NSLayoutAttributeHeight multiplier:1 constant:0];
    [self.view addConstraints:@[leftC,rightC,bottomC,heightC]];
    
}

///扫描动画
- (void) setAnimation{

    self.bottomConstraint.constant = 0;
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:1 animations:^{
        [UIView setAnimationRepeatCount:MAXFLOAT];
        self.bottomConstraint.constant = self.scanView.frame.size.height;
        [self.view layoutIfNeeded];
    }];
}
#pragma 扫描功能

///添加扫描
- (void) addScanFoundation{
    
    if (![self.session canAddInput:self.deviceInput]) {
        NSLog(@"无输入设备");
        return;
    }
    if (![self.session canAddOutput:self.metadataOutput]) {
        NSLog(@"无输出数据");
        return;
    }
    //添加输入设备
    [self.session addInput:self.deviceInput];
    //添加输出
    [self.session addOutput:self.metadataOutput];
    //设置输出数据
    self.metadataOutput.metadataObjectTypes = self.metadataOutput.availableMetadataObjectTypes;
    [self.metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    
    //启动会话
    [self.session startRunning];
    //添加绘画图层
    [self.view.layer insertSublayer:self.drawLayer atIndex:0];
    //添加预览图层
    [self.view.layer insertSublayer:self.videoPreviewLayer atIndex:0];
}

///代理
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    

    
    /*
    if ( CFAbsoluteTimeGetCurrent() - self.time < 2) {
        return;
    }
    self.time = CFAbsoluteTimeGetCurrent();
    */
    
    static int index = 0;
    NSLog(@"%d",index++);
    
    //清理图层
    [self clearTheDrawLayer];
    
    for (AVMetadataMachineReadableCodeObject *object in metadataObjects) {
        AVMetadataMachineReadableCodeObject *obj =(AVMetadataMachineReadableCodeObject *) [self.videoPreviewLayer transformedMetadataObjectForMetadataObject:object];
        
        
       
            [self drawTheLayerWithCodeObject:obj];
            self.mylable.text = obj.stringValue;


        
    }
    

    
}
///绘制路径
- (void) drawTheLayerWithCodeObject:(AVMetadataMachineReadableCodeObject *)codeObject{
    
    if (codeObject.corners == nil) {
        NSLog(@"无数据");
        return;
    }
    
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.lineWidth = 4;
    layer.strokeColor = [UIColor brownColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
#pragma    重要.CGPath
    layer.path = [self getThePathWithCorners:codeObject.corners].CGPath;
    [self.drawLayer addSublayer:layer];
}

///获取点
- (UIBezierPath *)getThePathWithCorners:(NSArray *)corners{
    
    UIBezierPath *path = [UIBezierPath bezierPath];
    CGPoint point = CGPointZero;
    int index = 0 ;
    CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)corners[index ++] , &point);
    [path moveToPoint:point];
    //循环
    while (index < corners.count) {
        CGPointMakeWithDictionaryRepresentation((CFDictionaryRef)corners[index ++] , &point);
        [path addLineToPoint:point];
    }
    [path closePath];
    return path;
}
///清理图层，以便只获取一个图形
-  (void)clearTheDrawLayer{
    

    if (self.drawLayer.sublayers == nil) {
        
        return;
    }
    for (CALayer *layer in self.drawLayer.sublayers) {
        [layer removeFromSuperlayer];
    }
    
    
}





#pragma  懒加载

- (AVCaptureSession *)session
{
    if (!_session) {
        _session = [[AVCaptureSession alloc]init];
    }
    return _session;
}

- (AVCaptureDeviceInput *)deviceInput
{
    if (!_deviceInput) {
        
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if (!device) {
            return nil;
        }
        _deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    }
    return _deviceInput;
}
- (AVCaptureMetadataOutput *)metadataOutput
{
    if (!_metadataOutput) {
        _metadataOutput = [[AVCaptureMetadataOutput alloc]init];
    }
    return _metadataOutput;
}
- (AVCaptureVideoPreviewLayer *)videoPreviewLayer
{
    if (!_videoPreviewLayer) {
        _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
        _videoPreviewLayer.frame =  self.view.frame;
    }
    return _videoPreviewLayer;
}
-(CALayer *)drawLayer{
    
    if (!_drawLayer) {
        _drawLayer = [CALayer layer];
        _drawLayer.frame = self.view.bounds;
    }
    return _drawLayer;
}

@end
